/*   
 * Copyright (c) 2010-2020 DMGIS Ltd. All Rights Reserved.   
 *   
 * This software is the confidential and proprietary information of   
 * DMGIS. You shall not disclose such Confidential Information   
 * and shall use it only in accordance with the terms of the agreements   
 * you entered into with DMGIS.   
 *   
 */
package com.dmgis.qxfw.dataservice.pages.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.RequestDataBySelect;
import com.dmgis.qxfw.dataservice.businessservice.common.util.*;
import com.dmgis.qxfw.dataservice.businessservice.controller.ProcessRequestController;
import com.dmgis.qxfw.dataservice.commonservice.utils.MD5Utils;
import com.dmgis.qxfw.dataservice.commonservice.utils.RedisUtil;
import com.dmgis.qxfw.dataservice.commonservice.utils.StringUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import net.sf.json.util.JSONUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class LoginInterceptor implements HandlerInterceptor {
	ProcessRequestController pc = new ProcessRequestController();


	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// 执行完毕，返回前拦截
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// 在处理过程中，执行拦截
	}

	/**
	 * 校验签名
	 * @param token
	 * @param timestamp
	 * @param sign
	 * @return boolean
	 */
	public boolean checkSign(String token, String timestamp,String sign) throws ParseException {
		//取出缓存中的token
		Jedis jedis = RedisUtil.getJedis();
		String userToken = jedis.get(token);
		if (!StringUtil.IsNullOrEmpty(userToken)) {
			//验证时间戳和当前时间相差是否小于1分钟
			long inputTime = Long.parseLong(timestamp);
			if (System.currentTimeMillis() - inputTime < 60 * 1000) {
				//通过token和timestamp计算sign
				String signStr = generate(token, timestamp);
				if (sign.equals(signStr)) {
					//验证成功
					return true;
				}
			}
		}
		return false;
	}
	/**
	 * 根据token和timestamp生成sign
	 * @param token
	 * @param timestamp
	 * @return string
	 */
	public String generate(String token, String timestamp) {
		//token+timestamp拼接，进行sha1加密 ，字符串重新排序，再md52次加密，返回签名
		StringBuilder singStr = new StringBuilder();
		StringBuilder strChar = new StringBuilder();
		singStr.append(token).append(timestamp);
		//进行sha1加密
		String sha1Str = DigestUtils.sha1Hex(singStr.toString());
		//字符串重排序按照
		char[]sha1Char = sha1Str.toCharArray();
		Arrays.sort(sha1Char);
		for (char cr : sha1Char) {
			strChar.append(cr);
		}
		//Md5二次加密返回签名
		String encode = MD5Utils.MD5Encode(strChar.toString(), "utf-8");
		return encode;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		// 在拦截点执行前拦截，如果返回true则不执行拦截点后的操作（拦截成功）
		// 返回false则不执行拦截
				HttpSession session = request.getSession();
				String uri = request.getRequestURI(); // 获取登录的uri，这个是不进行拦截的
				System.out.println(uri);

				// 拦截其他行业气象的controller层，如disaster等
				// 放行登陆
				boolean result = false;
				String token = request.getHeader("token");
				String timestamp = request.getHeader("timestamp");
				String sign = request.getHeader("sign");
				if (!StringUtil.IsNullOrEmpty(token)) {
					Jedis jedis = null;
					try {
						jedis = RedisUtil.getJedis();
						String userToken = jedis.get(token);
						if (!StringUtil.IsNullOrEmpty(userToken)) {
							boolean flag = checkSign(token, timestamp, sign);
							if (flag) {
								//验证
								return true;
							}
						} else {
							//token失效
							response.setCharacterEncoding("UTF-8");
							response.setContentType("application/ json ; charset=UTF-8");
							response.setStatus(505);
							return false;
						}
					} catch (Exception e) {
						System.out.println(e.getMessage());
					} finally {
						RedisUtil.returnBrokenResource(jedis);
					}
				}

				String targetUrl = DbConfig.IP + request.getRequestURI();
				if (null != request.getQueryString()) {
					targetUrl += "?" + request.getQueryString();//获取全路径
				}
				if (targetUrl.contains("?") && !targetUrl.contains("login") && !targetUrl.contains("prosrv") && !targetUrl.contains("index") && !targetUrl.contains("getVerify") && !targetUrl.contains("getUrl") || targetUrl.contains("queryInfo") || targetUrl.contains("pictureInfo"))
					request.getSession().setAttribute("targetUrl", targetUrl);

				if (uri.contains("login") || uri.contains("prosrv") || uri.contains("index") || uri.contains("getVerify") || uri.contains("getUrl") || targetUrl.contains("queryInfo") || targetUrl.contains("pictureInfo")) {
					result = true;
				} else {
					String userName = String.valueOf(session.getAttribute("userName"));
					String Site = String.valueOf(session.getAttribute("wbSite"));
					String permission = String.valueOf(session.getAttribute("permission"));
					if (session.getAttribute("userName") != null && session.getAttribute("wbSite") != null && (session.getAttribute("permission") != null || session.getAttribute("permission") != "")) {
						// 登录成功不拦截
						// 判断website是否有权限
						//String userName=session.getAttribute("userName").toString();
						String wbSite = session.getAttribute("wbSite").toString();
						String strTargetUrl = request.getSession().getAttribute("targetUrl").toString();
						String[] uriParams = uri.split("/");
						if (uriParams.length == 4) {
							String controllerName = uriParams[2];
							String strRole = session.getAttribute("permission").toString();
							if (strTargetUrl.contains("xtyj")) {
								if ((!strRole.contains("应急") && !strRole.contains("管理")) || !"common".equals(controllerName) && !"qxinfo".equals(controllerName) && !"xtgt".equals(controllerName) && !"xtsl".equals(controllerName) && !"xtnl".equals(controllerName) && !"xthx".equals(controllerName) && !"xtyj".equals(controllerName) && !"xtly".equals(controllerName)) {// 网站路径没有包含controller层名称，说明用户和行业气象不匹配，没有权限
									//redirect(request, response);
									result = false;
								} else {
									result = true;
								}
							} else if (strTargetUrl.contains("xttour")) {
								if ((!strRole.contains("旅游") && !strRole.contains("管理")) || !"common".equals(controllerName) && !"qxinfo".equals(controllerName) && !"xtgt".equals(controllerName) && !"xtly".equals(controllerName) && !"xthb".equals(controllerName) && !"xttour".equals(controllerName) && !"xtjt".equals(controllerName)) {// 网站路径没有包含controller层名称，说明用户和行业气象不匹配，没有权限
									// redirect(request, response);
									result = false;
								} else {
									result = true;
								}
							} else if (strTargetUrl.contains("xtjt")) {
								if ((!strRole.contains("交通") && !strRole.contains("管理")) || !"common".equals(controllerName) && !"qxinfo".equals(controllerName) && !"xtrb".equals(controllerName) && !"xtgt".equals(controllerName) && !"xtjt".equals(controllerName) && !"xttour".equals(controllerName)) {// 网站路径没有包含controller层名称，说明用户和行业气象不匹配，没有权限
									//redirect(request, response);
									result = false;
								} else {
									result = true;
								}
							} else if (strTargetUrl.contains("xtsl")) {
								if ((!strRole.contains("水利") && !strRole.contains("管理")) || !"xtsl".equals(controllerName) && !"qxinfo".equals(controllerName) && !"ctstour".equals(controllerName) && !"xttour".equals(controllerName) && !"xtgt".equals(controllerName) && !"xtly".equals(controllerName) && !"xtdl".equals(controllerName) && !"xthb".equals(controllerName) && !"xthx".equals(controllerName) && !"common".equals(controllerName)) {// 网站路径没有包含controller层名称，说明用户和行业气象不匹配，没有权限
									//redirect(request, response);
									return false;
								} else {
									result = true;
								}
							} else if (strTargetUrl.contains("xtrb")) {
								if ((!strRole.contains("保险") && !strRole.contains("管理")) || !"xtrb".equals(controllerName) && !"xtnl".equals(controllerName) && !"xtsl".equals(controllerName) && !"qxinfo".equals(controllerName) && !"ctstour".equals(controllerName) && !"xttour".equals(controllerName) && !"xtgt".equals(controllerName) && !"xtly".equals(controllerName) && !"xtdl".equals(controllerName) && !"xthb".equals(controllerName) && !"xthx".equals(controllerName) && !"common".equals(controllerName)) {// 网站路径没有包含controller层名称，说明用户和行业气象不匹配，没有权限
									//redirect(request, response);
									result = false;
								} else {
									result = true;
								}
							} else if (strTargetUrl.contains("xtgt")) {
								if ((!strRole.contains("国土") && !strRole.contains("管理")) || !"qxinfo".equals(controllerName) && !wbSite.contains(controllerName) && !"common".equals(controllerName) && !"xtgt".equals(controllerName) && !"xtnl".equals(controllerName) && !"xtsl".equals(controllerName)) {// 网站路径没有包含controller层名称，说明用户和行业气象不匹配，没有权限
									//redirect(request, response);
									result = false;
								} else {
									result = true;
								}
							} else if (strTargetUrl.contains("xtly")) {
								if ((!strRole.contains("林业") && !strRole.contains("管理")) || !"qxinfo".equals(controllerName) && !wbSite.contains(controllerName) && !"common".equals(controllerName) && !"xtgt".equals(controllerName) && !"xtnl".equals(controllerName) && !"xtly".equals(controllerName) && !"xtyj".equals(controllerName) && !"xtsl".equals(controllerName)) {// 网站路径没有包含controller层名称，说明用户和行业气象不匹配，没有权限
									//redirect(request, response);
									result = false;
								} else {
									result = true;
								}
							} else if (strTargetUrl.contains("xtdl")) {
								if ((!strRole.contains("电力") && !strRole.contains("管理")) || !"qxinfo".equals(controllerName) && !wbSite.contains(controllerName) && !"common".equals(controllerName) && !"xtgt".equals(controllerName) && !"xtnl".equals(controllerName) && !"xtdl".equals(controllerName)) {// 网站路径没有包含controller层名称，说明用户和行业气象不匹配，没有权限
									//redirect(request, response);
									result = false;
								} else {
									result = true;
								}
							} else if (strTargetUrl.contains("ctstour")) {
								if ((!strRole.contains("城头山") && !strRole.contains("管理")) || !"qxinfo".equals(controllerName) && !wbSite.contains(controllerName) && !"common".equals(controllerName) && !"xtgt".equals(controllerName) && !"xtnl".equals(controllerName) && !"Tower".equals(controllerName) && !"xtrb".equals(controllerName) && !"xtdl".equals(controllerName) && !"ctstour".equals(controllerName) && !"xthb".equals(controllerName) && !"xttour".equals(controllerName)) {// 网站路径没有包含controller层名称，说明用户和行业气象不匹配，没有权限
									//redirect(request, response);
									result = false;
								} else {
									result = true;
								}
							} else if (strTargetUrl.contains("xthb")) {
								if ((!strRole.contains("环保") && !strRole.contains("管理")) || !"qxinfo".equals(controllerName) && !wbSite.contains(controllerName) && !"common".equals(controllerName) && !"xtgt".equals(controllerName) && !"xtnl".equals(controllerName) && !"xthb".equals(controllerName) && !"xtyj".equals(controllerName)) {// 网站路径没有包含controller层名称，说明用户和行业气象不匹配，没有权限
									//redirect(request, response);
									result = false;
								} else {
									result = true;
								}
							} else if (strTargetUrl.contains("xtnl")) {
								if ((!strRole.contains("市政") && !strRole.contains("管理")) || !"qxinfo".equals(controllerName) && !wbSite.contains(controllerName) && !"common".equals(controllerName) && !"xtgt".equals(controllerName) && !"xtnl".equals(controllerName) && !"xtsl".equals(controllerName)) {// 网站路径没有包含controller层名称，说明用户和行业气象不匹配，没有权限
									//redirect(request, response);
									result = false;
								} else {
									result = true;
								}
							} else {
								if (!"qxinfo".equals(controllerName) && !wbSite.contains(controllerName) && !"common".equals(controllerName) && !"xtgt".equals(controllerName) && !"xtnl".equals(controllerName) && !"xtdl".equals(controllerName) && !"xtjt".equals(controllerName) && !"xtyj".equals(controllerName) && !"xtly".equals(controllerName) && !"Tower".equals(controllerName)) {// 网站路径没有包含controller层名称，说明用户和行业气象不匹配，没有权限
									//redirect(request, response);
									result = false;
								} else {
									result = true;
								}
							}
						} else {
							//result=true;
							String strRole = session.getAttribute("permission").toString();
							if (strTargetUrl.contains("xtyj")) {
								if ((!strRole.contains("应急") && !strRole.contains("管理"))) {
									result = false;
								} else {
									result = true;
								}
							} else if (strTargetUrl.contains("xttour")) {
								if ((!strRole.contains("旅游") && !strRole.contains("管理"))) {
									result = false;
								} else {
									result = true;
								}
							} else if (strTargetUrl.contains("xtjt")) {
								if ((!strRole.contains("交通") && !strRole.contains("管理"))) {// 网站路径没有包含controller层名称，说明用户和行业气象不匹配，没有权限
									//redirect(request, response);
									result = false;
								} else {
									result = true;
								}
							} else if (strTargetUrl.contains("xtsl")) {
								if ((!strRole.contains("水利") && !strRole.contains("管理"))) {
									result = false;
								} else {
									result = true;
								}
							} else if (strTargetUrl.contains("xtrb")) {
								if ((!strRole.contains("保险") && !strRole.contains("管理"))) {
									result = false;
								} else {
									result = true;
								}
							} else if (strTargetUrl.contains("xtgt")) {
								if ((!strRole.contains("国土") && !strRole.contains("管理"))) {
									result = false;
								} else {
									result = true;
								}
							} else if (strTargetUrl.contains("xtly")) {
								if ((!strRole.contains("林业") && !strRole.contains("管理"))) {
									result = false;
								} else {
									result = true;
								}
							} else if (strTargetUrl.contains("xtdl")) {
								if ((!strRole.contains("电力") && !strRole.contains("管理"))) {
									result = false;
								} else {
									result = true;
								}
							} else if (strTargetUrl.contains("ctstour")) {
								if ((!strRole.contains("城头山") && !strRole.contains("管理"))) {
									result = false;
								} else {
									result = true;
								}
							} else if (strTargetUrl.contains("xthb")) {
								if ((!strRole.contains("环保") && !strRole.contains("管理"))) {
									result = false;
								} else {
									result = true;
								}
							} else if (strTargetUrl.contains("xtnl")) {
								if ((!strRole.contains("市政") && !strRole.contains("管理"))) {
									result = false;
								} else {
									result = true;
								}
							}
						}
					} else {

						result = false;
					}
					if (result == false) {
						// 拦截后进入登录页面
						redirect(request, response);
					}
				}
				return result;
			}

			// 对于请求是ajax请求重定向问题的处理方法
			public void redirect (HttpServletRequest request, HttpServletResponse response) throws IOException {
				// 获取当前请求的路径
				String basePath = DbConfig.IP
						+ request.getContextPath();

				String strTargetUrl = request.getSession().getAttribute("targetUrl").toString();
				response.sendRedirect(basePath + "/login.jsp?targetUrl=" + URLEncoder.encode(strTargetUrl, "utf-8"));
			}

	}